package com.ipzoe.file.config;

import com.ipzoe.file.config.properties.FileServerProperties;
import com.ipzoe.file.domain.FileInfoDO;
import com.ipzoe.file.service.AbstractFileDOService;
import com.obs.services.ObsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Configuration
@EnableConfigurationProperties(FileServerProperties.class)
@ConditionalOnProperty(prefix = "ruoyi.file-server",name = "type", havingValue = "huaweiyun")
public class HuaweiyunOBSAutoConfigure {

    @Autowired
    private FileServerProperties fileServerProperties;

    @Bean
    public ObsClient obsClient(FileServerProperties fileServerProperties){
        return new ObsClient(fileServerProperties.getObs().getAk(), fileServerProperties.getObs().getSk(),fileServerProperties.getObs().getEndPoint());
    }

    @Service
    public class HuaweiyunOBSDOServiceImpl extends AbstractFileDOService {

        @Autowired
        private ObsClient obsClient;

        @Override
        protected String fileType() {
            return fileServerProperties.getType();
        }

        @Override
        protected void uploadFile(MultipartFile file, FileInfoDO fileInfo) throws IOException {
            obsClient.putObject(fileServerProperties.getObs().getBucketName(), fileInfo.getPath(), file.getInputStream());
            fileInfo.setUrl(fileServerProperties.getObs().getDomain() + File.separator + fileInfo.getPath());
        }

        @Override
        protected boolean deleteFile(FileInfoDO fileInfo) {
            obsClient.deleteObject(fileServerProperties.getObs().getBucketName(), fileInfo.getPath());
            return true;
        }
    }
}
